
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Writing custom model fields &#8212; Django 2.2.12.dev20200304094918 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="Custom Lookups" href="custom-lookups.html" />
    <link rel="prev" title="Writing custom django-admin commands" href="custom-management-commands.html" />



 
<script type="text/javascript" src="../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 2.2.12.dev20200304094918 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="custom-management-commands.html" title="Writing custom &lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;django-admin&lt;/span&gt;&lt;/code&gt; commands">previous</a>
     |
    <a href="index.html" title="“How-to” guides" accesskey="U">up</a>
   |
    <a href="custom-lookups.html" title="Custom Lookups">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="howto-custom-model-fields">
            
  <div class="section" id="s-writing-custom-model-fields">
<span id="writing-custom-model-fields"></span><h1>Writing custom model fields<a class="headerlink" href="#writing-custom-model-fields" title="Permalink to this headline">¶</a></h1>
<div class="section" id="s-introduction">
<span id="introduction"></span><h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../topics/db/models.html"><span class="doc">model reference</span></a> documentation explains how to use
Django’s standard field classes – <a class="reference internal" href="../ref/models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a>,
<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField" title="django.db.models.DateField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateField</span></code></a>, etc. For many purposes, those classes are
all you’ll need. Sometimes, though, the Django version won’t meet your precise
requirements, or you’ll want to use a field that is entirely different from
those shipped with Django.</p>
<p>Django’s built-in field types don’t cover every possible database column type –
only the common types, such as <code class="docutils literal notranslate"><span class="pre">VARCHAR</span></code> and <code class="docutils literal notranslate"><span class="pre">INTEGER</span></code>. For more obscure
column types, such as geographic polygons or even user-created types such as
<a class="reference external" href="https://www.postgresql.org/docs/current/sql-createtype.html">PostgreSQL custom types</a>, you can define your own Django <code class="docutils literal notranslate"><span class="pre">Field</span></code> subclasses.</p>
<p>Alternatively, you may have a complex Python object that can somehow be
serialized to fit into a standard database column type. This is another case
where a <code class="docutils literal notranslate"><span class="pre">Field</span></code> subclass will help you use your object with your models.</p>
<div class="section" id="s-our-example-object">
<span id="our-example-object"></span><h3>Our example object<a class="headerlink" href="#our-example-object" title="Permalink to this headline">¶</a></h3>
<p>Creating custom fields requires a bit of attention to detail. To make things
easier to follow, we’ll use a consistent example throughout this document:
wrapping a Python object representing the deal of cards in a hand of <a class="reference external" href="https://en.wikipedia.org/wiki/Contract_bridge">Bridge</a>.
Don’t worry, you don’t have to know how to play Bridge to follow this example.
You only need to know that 52 cards are dealt out equally to four players, who
are traditionally called <em>north</em>, <em>east</em>, <em>south</em> and <em>west</em>.  Our class looks
something like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Hand</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;A hand of cards (bridge style)&quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">north</span><span class="p">,</span> <span class="n">east</span><span class="p">,</span> <span class="n">south</span><span class="p">,</span> <span class="n">west</span><span class="p">):</span>
        <span class="c1"># Input parameters are lists of cards (&#39;Ah&#39;, &#39;9s&#39;, etc.)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">north</span> <span class="o">=</span> <span class="n">north</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">east</span> <span class="o">=</span> <span class="n">east</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">south</span> <span class="o">=</span> <span class="n">south</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">west</span> <span class="o">=</span> <span class="n">west</span>

    <span class="c1"># ... (other possibly useful methods omitted) ...</span>
</pre></div>
</div>
<p>This is just an ordinary Python class, with nothing Django-specific about it.
We’d like to be able to do things like this in our models (we assume the
<code class="docutils literal notranslate"><span class="pre">hand</span></code> attribute on the model is an instance of <code class="docutils literal notranslate"><span class="pre">Hand</span></code>):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">example</span> <span class="o">=</span> <span class="n">MyModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">example</span><span class="o">.</span><span class="n">hand</span><span class="o">.</span><span class="n">north</span><span class="p">)</span>

<span class="n">new_hand</span> <span class="o">=</span> <span class="n">Hand</span><span class="p">(</span><span class="n">north</span><span class="p">,</span> <span class="n">east</span><span class="p">,</span> <span class="n">south</span><span class="p">,</span> <span class="n">west</span><span class="p">)</span>
<span class="n">example</span><span class="o">.</span><span class="n">hand</span> <span class="o">=</span> <span class="n">new_hand</span>
<span class="n">example</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>We assign to and retrieve from the <code class="docutils literal notranslate"><span class="pre">hand</span></code> attribute in our model just like
any other Python class. The trick is to tell Django how to handle saving and
loading such an object.</p>
<p>In order to use the <code class="docutils literal notranslate"><span class="pre">Hand</span></code> class in our models, we <strong>do not</strong> have to change
this class at all. This is ideal, because it means you can easily write
model support for existing classes where you cannot change the source code.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">You might only be wanting to take advantage of custom database column
types and deal with the data as standard Python types in your models;
strings, or floats, for example. This case is similar to our <code class="docutils literal notranslate"><span class="pre">Hand</span></code>
example and we’ll note any differences as we go along.</p>
</div>
</div>
</div>
<div class="section" id="s-background-theory">
<span id="background-theory"></span><h2>Background theory<a class="headerlink" href="#background-theory" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-database-storage">
<span id="database-storage"></span><h3>Database storage<a class="headerlink" href="#database-storage" title="Permalink to this headline">¶</a></h3>
<p>The simplest way to think of a model field is that it provides a way to take a
normal Python object – string, boolean, <code class="docutils literal notranslate"><span class="pre">datetime</span></code>, or something more
complex like <code class="docutils literal notranslate"><span class="pre">Hand</span></code> – and convert it to and from a format that is useful
when dealing with the database (and serialization, but, as we’ll see later,
that falls out fairly naturally once you have the database side under control).</p>
<p>Fields in a model must somehow be converted to fit into an existing database
column type. Different databases provide different sets of valid column types,
but the rule is still the same: those are the only types you have to work
with. Anything you want to store in the database must fit into one of
those types.</p>
<p>Normally, you’re either writing a Django field to match a particular database
column type, or there’s a fairly straightforward way to convert your data to,
say, a string.</p>
<p>For our <code class="docutils literal notranslate"><span class="pre">Hand</span></code> example, we could convert the card data to a string of 104
characters by concatenating all the cards together in a pre-determined order –
say, all the <em>north</em> cards first, then the <em>east</em>, <em>south</em> and <em>west</em> cards. So
<code class="docutils literal notranslate"><span class="pre">Hand</span></code> objects can be saved to text or character columns in the database.</p>
</div>
<div class="section" id="s-what-does-a-field-class-do">
<span id="what-does-a-field-class-do"></span><h3>What does a field class do?<a class="headerlink" href="#what-does-a-field-class-do" title="Permalink to this headline">¶</a></h3>
<p>All of Django’s fields (and when we say <em>fields</em> in this document, we always
mean model fields and not <a class="reference internal" href="../ref/forms/fields.html"><span class="doc">form fields</span></a>) are subclasses
of <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.db.models.Field</span></code></a>. Most of the information that Django records
about a field is common to all fields – name, help text, uniqueness and so
forth. Storing all that information is handled by <code class="docutils literal notranslate"><span class="pre">Field</span></code>. We’ll get into the
precise details of what <code class="docutils literal notranslate"><span class="pre">Field</span></code> can do later on; for now, suffice it to say
that everything descends from <code class="docutils literal notranslate"><span class="pre">Field</span></code> and then customizes key pieces of the
class behavior.</p>
<p>It’s important to realize that a Django field class is not what is stored in
your model attributes. The model attributes contain normal Python objects. The
field classes you define in a model are actually stored in the <code class="docutils literal notranslate"><span class="pre">Meta</span></code> class
when the model class is created (the precise details of how this is done are
unimportant here). This is because the field classes aren’t necessary when
you’re just creating and modifying attributes. Instead, they provide the
machinery for converting between the attribute value and what is stored in the
database or sent to the <a class="reference internal" href="../topics/serialization.html"><span class="doc">serializer</span></a>.</p>
<p>Keep this in mind when creating your own custom fields. The Django <code class="docutils literal notranslate"><span class="pre">Field</span></code>
subclass you write provides the machinery for converting between your Python
instances and the database/serializer values in various ways (there are
differences between storing a value and using a value for lookups, for
example). If this sounds a bit tricky, don’t worry – it will become clearer in
the examples below. Just remember that you will often end up creating two
classes when you want a custom field:</p>
<ul class="simple">
<li>The first class is the Python object that your users will manipulate.
They will assign it to the model attribute, they will read from it for
displaying purposes, things like that. This is the <code class="docutils literal notranslate"><span class="pre">Hand</span></code> class in our
example.</li>
<li>The second class is the <code class="docutils literal notranslate"><span class="pre">Field</span></code> subclass. This is the class that knows
how to convert your first class back and forth between its permanent
storage form and the Python form.</li>
</ul>
</div>
</div>
<div class="section" id="s-writing-a-field-subclass">
<span id="writing-a-field-subclass"></span><h2>Writing a field subclass<a class="headerlink" href="#writing-a-field-subclass" title="Permalink to this headline">¶</a></h2>
<p>When planning your <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> subclass, first give some
thought to which existing <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> class your new field
is most similar to. Can you subclass an existing Django field and save yourself
some work? If not, you should subclass the <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a>
class, from which everything is descended.</p>
<p>Initializing your new field is a matter of separating out any arguments that are
specific to your case from the common arguments and passing the latter to the
<code class="docutils literal notranslate"><span class="pre">__init__()</span></code> method of <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> (or your parent
class).</p>
<p>In our example, we’ll call our field <code class="docutils literal notranslate"><span class="pre">HandField</span></code>. (It’s a good idea to call
your <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> subclass <code class="docutils literal notranslate"><span class="pre">&lt;Something&gt;Field</span></code>, so it’s
easily identifiable as a <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> subclass.) It doesn’t
behave like any existing field, so we’ll subclass directly from
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>

    <span class="n">description</span> <span class="o">=</span> <span class="s2">&quot;A hand of cards (bridge style)&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">kwargs</span><span class="p">[</span><span class="s1">&#39;max_length&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">104</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>Our <code class="docutils literal notranslate"><span class="pre">HandField</span></code> accepts most of the standard field options (see the list
below), but we ensure it has a fixed length, since it only needs to hold 52
card values plus their suits; 104 characters in total.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Many of Django’s model fields accept options that they don’t do anything
with. For example, you can pass both
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.editable" title="django.db.models.Field.editable"><code class="xref py py-attr docutils literal notranslate"><span class="pre">editable</span></code></a> and
<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField.auto_now" title="django.db.models.DateField.auto_now"><code class="xref py py-attr docutils literal notranslate"><span class="pre">auto_now</span></code></a> to a
<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField" title="django.db.models.DateField"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.db.models.DateField</span></code></a> and it will simply ignore the
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.editable" title="django.db.models.Field.editable"><code class="xref py py-attr docutils literal notranslate"><span class="pre">editable</span></code></a> parameter
(<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField.auto_now" title="django.db.models.DateField.auto_now"><code class="xref py py-attr docutils literal notranslate"><span class="pre">auto_now</span></code></a> being set implies
<code class="docutils literal notranslate"><span class="pre">editable=False</span></code>). No error is raised in this case.</p>
<p class="last">This behavior simplifies the field classes, because they don’t need to
check for options that aren’t necessary. They just pass all the options to
the parent class and then don’t use them later on. It’s up to you whether
you want your fields to be more strict about the options they select, or to
use the simpler, more permissive behavior of the current fields.</p>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">Field.__init__()</span></code> method takes the following parameters:</p>
<ul class="simple">
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.verbose_name" title="django.db.models.Field.verbose_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">verbose_name</span></code></a></li>
<li><code class="docutils literal notranslate"><span class="pre">name</span></code></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><code class="xref py py-attr docutils literal notranslate"><span class="pre">primary_key</span></code></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><code class="xref py py-attr docutils literal notranslate"><span class="pre">max_length</span></code></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.unique" title="django.db.models.Field.unique"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique</span></code></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.blank" title="django.db.models.Field.blank"><code class="xref py py-attr docutils literal notranslate"><span class="pre">blank</span></code></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.null" title="django.db.models.Field.null"><code class="xref py py-attr docutils literal notranslate"><span class="pre">null</span></code></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_index" title="django.db.models.Field.db_index"><code class="xref py py-attr docutils literal notranslate"><span class="pre">db_index</span></code></a></li>
<li><code class="docutils literal notranslate"><span class="pre">rel</span></code>: Used for related fields (like <a class="reference internal" href="../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>). For advanced
use only.</li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.default" title="django.db.models.Field.default"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default</span></code></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.editable" title="django.db.models.Field.editable"><code class="xref py py-attr docutils literal notranslate"><span class="pre">editable</span></code></a></li>
<li><code class="docutils literal notranslate"><span class="pre">serialize</span></code>: If <code class="docutils literal notranslate"><span class="pre">False</span></code>, the field will not be serialized when the model
is passed to Django’s <a class="reference internal" href="../topics/serialization.html"><span class="doc">serializers</span></a>. Defaults to
<code class="docutils literal notranslate"><span class="pre">True</span></code>.</li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.unique_for_date" title="django.db.models.Field.unique_for_date"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique_for_date</span></code></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.unique_for_month" title="django.db.models.Field.unique_for_month"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique_for_month</span></code></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.unique_for_year" title="django.db.models.Field.unique_for_year"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique_for_year</span></code></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.choices" title="django.db.models.Field.choices"><code class="xref py py-attr docutils literal notranslate"><span class="pre">choices</span></code></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.help_text" title="django.db.models.Field.help_text"><code class="xref py py-attr docutils literal notranslate"><span class="pre">help_text</span></code></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_column" title="django.db.models.Field.db_column"><code class="xref py py-attr docutils literal notranslate"><span class="pre">db_column</span></code></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_tablespace" title="django.db.models.Field.db_tablespace"><code class="xref py py-attr docutils literal notranslate"><span class="pre">db_tablespace</span></code></a>: Only for index creation, if the
backend supports <a class="reference internal" href="../topics/db/tablespaces.html"><span class="doc">tablespaces</span></a>. You can usually
ignore this option.</li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.auto_created" title="django.db.models.Field.auto_created"><code class="xref py py-attr docutils literal notranslate"><span class="pre">auto_created</span></code></a>: <code class="docutils literal notranslate"><span class="pre">True</span></code> if the field was
automatically created, as for the <a class="reference internal" href="../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><code class="xref py py-class docutils literal notranslate"><span class="pre">OneToOneField</span></code></a>
used by model inheritance. For advanced use only.</li>
</ul>
<p>All of the options without an explanation in the above list have the same
meaning they do for normal Django fields. See the <a class="reference internal" href="../ref/models/fields.html"><span class="doc">field documentation</span></a> for examples and details.</p>
<div class="section" id="s-field-deconstruction">
<span id="s-custom-field-deconstruct-method"></span><span id="field-deconstruction"></span><span id="custom-field-deconstruct-method"></span><h3>Field deconstruction<a class="headerlink" href="#field-deconstruction" title="Permalink to this headline">¶</a></h3>
<p>The counterpoint to writing your <code class="docutils literal notranslate"><span class="pre">__init__()</span></code> method is writing the
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.deconstruct" title="django.db.models.Field.deconstruct"><code class="xref py py-meth docutils literal notranslate"><span class="pre">deconstruct()</span></code></a> method. It’s used during <a class="reference internal" href="../topics/migrations.html"><span class="doc">model migrations</span></a> to tell Django how to take an instance of your new field
and reduce it to a serialized form - in particular, what arguments to pass to
<code class="docutils literal notranslate"><span class="pre">__init__()</span></code> to re-create it.</p>
<p>If you haven’t added any extra options on top of the field you inherited from,
then there’s no need to write a new <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code> method. If, however,
you’re changing the arguments passed in <code class="docutils literal notranslate"><span class="pre">__init__()</span></code> (like we are in
<code class="docutils literal notranslate"><span class="pre">HandField</span></code>), you’ll need to supplement the values being passed.</p>
<p>The contract of <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code> is simple; it returns a tuple of four items:
the field’s attribute name, the full import path of the field class, the
positional arguments (as a list), and the keyword arguments (as a dict). Note
this is different from the <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code> method <a class="reference internal" href="../topics/migrations.html#custom-deconstruct-method"><span class="std std-ref">for custom classes</span></a> which returns a tuple of three things.</p>
<p>As a custom field author, you don’t need to care about the first two values;
the base <code class="docutils literal notranslate"><span class="pre">Field</span></code> class has all the code to work out the field’s attribute
name and import path. You do, however, have to care about the positional
and keyword arguments, as these are likely the things you are changing.</p>
<p>For example, in our <code class="docutils literal notranslate"><span class="pre">HandField</span></code> class we’re always forcibly setting
max_length in <code class="docutils literal notranslate"><span class="pre">__init__()</span></code>. The <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code> method on the base <code class="docutils literal notranslate"><span class="pre">Field</span></code>
class will see this and try to return it in the keyword arguments; thus,
we can drop it from the keyword arguments for readability:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">kwargs</span><span class="p">[</span><span class="s1">&#39;max_length&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">104</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">deconstruct</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">name</span><span class="p">,</span> <span class="n">path</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">deconstruct</span><span class="p">()</span>
        <span class="k">del</span> <span class="n">kwargs</span><span class="p">[</span><span class="s2">&quot;max_length&quot;</span><span class="p">]</span>
        <span class="k">return</span> <span class="n">name</span><span class="p">,</span> <span class="n">path</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span>
</pre></div>
</div>
<p>If you add a new keyword argument, you need to write code in <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code>
that puts its value into <code class="docutils literal notranslate"><span class="pre">kwargs</span></code> yourself. You should also omit the value
from <code class="docutils literal notranslate"><span class="pre">kwargs</span></code> when it isn’t necessary to reconstruct the state of the field,
such as when the default value is being used:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">CommaSepField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="s2">&quot;Implements comma-separated storage of lists&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">separator</span><span class="o">=</span><span class="s2">&quot;,&quot;</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">separator</span> <span class="o">=</span> <span class="n">separator</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">deconstruct</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">name</span><span class="p">,</span> <span class="n">path</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">deconstruct</span><span class="p">()</span>
        <span class="c1"># Only include kwarg if it&#39;s not the default</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">separator</span> <span class="o">!=</span> <span class="s2">&quot;,&quot;</span><span class="p">:</span>
            <span class="n">kwargs</span><span class="p">[</span><span class="s1">&#39;separator&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">separator</span>
        <span class="k">return</span> <span class="n">name</span><span class="p">,</span> <span class="n">path</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span>
</pre></div>
</div>
<p>More complex examples are beyond the scope of this document, but remember -
for any configuration of your Field instance, <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code> must return
arguments that you can pass to <code class="docutils literal notranslate"><span class="pre">__init__</span></code> to reconstruct that state.</p>
<p>Pay extra attention if you set new default values for arguments in the
<code class="docutils literal notranslate"><span class="pre">Field</span></code> superclass; you want to make sure they’re always included, rather
than disappearing if they take on the old default value.</p>
<p>In addition, try to avoid returning values as positional arguments; where
possible, return values as keyword arguments for maximum future compatibility.
Of course, if you change the names of things more often than their position
in the constructor’s argument list, you might prefer positional, but bear in
mind that people will be reconstructing your field from the serialized version
for quite a while (possibly years), depending how long your migrations live for.</p>
<p>You can see the results of deconstruction by looking in migrations that include
the field, and you can test deconstruction in unit tests by just deconstructing
and reconstructing the field:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">name</span><span class="p">,</span> <span class="n">path</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="n">my_field_instance</span><span class="o">.</span><span class="n">deconstruct</span><span class="p">()</span>
<span class="n">new_instance</span> <span class="o">=</span> <span class="n">MyField</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">my_field_instance</span><span class="o">.</span><span class="n">some_attribute</span><span class="p">,</span> <span class="n">new_instance</span><span class="o">.</span><span class="n">some_attribute</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-changing-a-custom-field-s-base-class">
<span id="changing-a-custom-field-s-base-class"></span><h3>Changing a custom field’s base class<a class="headerlink" href="#changing-a-custom-field-s-base-class" title="Permalink to this headline">¶</a></h3>
<p>You can’t change the base class of a custom field because Django won’t detect
the change and make a migration for it. For example, if you start with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">CustomCharField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>and then decide that you want to use <code class="docutils literal notranslate"><span class="pre">TextField</span></code> instead, you can’t change
the subclass like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">CustomCharField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Instead, you must create a new custom field class and update your models to
reference it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">CustomCharField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">):</span>
    <span class="o">...</span>

<span class="k">class</span> <span class="nc">CustomTextField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>As discussed in <a class="reference internal" href="../topics/migrations.html#migrations-removing-model-fields"><span class="std std-ref">removing fields</span></a>, you
must retain the original <code class="docutils literal notranslate"><span class="pre">CustomCharField</span></code> class as long as you have
migrations that reference it.</p>
</div>
<div class="section" id="s-documenting-your-custom-field">
<span id="documenting-your-custom-field"></span><h3>Documenting your custom field<a class="headerlink" href="#documenting-your-custom-field" title="Permalink to this headline">¶</a></h3>
<p>As always, you should document your field type, so users will know what it is.
In addition to providing a docstring for it, which is useful for developers,
you can also allow users of the admin app to see a short description of the
field type via the <a class="reference internal" href="../ref/contrib/admin/admindocs.html"><span class="doc">django.contrib.admindocs</span></a> application. To do this simply provide
descriptive text in a <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.description" title="django.db.models.Field.description"><code class="xref py py-attr docutils literal notranslate"><span class="pre">description</span></code></a> class attribute of your custom
field. In the above example, the description displayed by the <code class="docutils literal notranslate"><span class="pre">admindocs</span></code>
application for a <code class="docutils literal notranslate"><span class="pre">HandField</span></code> will be ‘A hand of cards (bridge style)’.</p>
<p>In the <a class="reference internal" href="../ref/contrib/admin/admindocs.html#module-django.contrib.admindocs" title="django.contrib.admindocs: Django's admin documentation generator."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.admindocs</span></code></a> display, the field description is
interpolated with <code class="docutils literal notranslate"><span class="pre">field.__dict__</span></code> which allows the description to
incorporate arguments of the field. For example, the description for
<a class="reference internal" href="../ref/models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a> is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">description</span> <span class="o">=</span> <span class="n">_</span><span class="p">(</span><span class="s2">&quot;String (up to </span><span class="si">%(max_length)s</span><span class="s2">)&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-useful-methods">
<span id="useful-methods"></span><h3>Useful methods<a class="headerlink" href="#useful-methods" title="Permalink to this headline">¶</a></h3>
<p>Once you’ve created your <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> subclass, you might
consider overriding a few standard methods, depending on your field’s behavior.
The list of methods below is in approximately decreasing order of importance,
so start from the top.</p>
<div class="section" id="s-custom-database-types">
<span id="s-id1"></span><span id="custom-database-types"></span><span id="id1"></span><h4>Custom database types<a class="headerlink" href="#custom-database-types" title="Permalink to this headline">¶</a></h4>
<p>Say you’ve created a PostgreSQL custom type called <code class="docutils literal notranslate"><span class="pre">mytype</span></code>. You can
subclass <code class="docutils literal notranslate"><span class="pre">Field</span></code> and implement the <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">db_type()</span></code></a> method, like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">MytypeField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;mytype&#39;</span>
</pre></div>
</div>
<p>Once you have <code class="docutils literal notranslate"><span class="pre">MytypeField</span></code>, you can use it in any model, just like any other
<code class="docutils literal notranslate"><span class="pre">Field</span></code> type:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">80</span><span class="p">)</span>
    <span class="n">something_else</span> <span class="o">=</span> <span class="n">MytypeField</span><span class="p">()</span>
</pre></div>
</div>
<p>If you aim to build a database-agnostic application, you should account for
differences in database column types. For example, the date/time column type
in PostgreSQL is called <code class="docutils literal notranslate"><span class="pre">timestamp</span></code>, while the same column in MySQL is called
<code class="docutils literal notranslate"><span class="pre">datetime</span></code>. The simplest way to handle this in a <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">db_type()</span></code></a>
method is to check the <code class="docutils literal notranslate"><span class="pre">connection.settings_dict['ENGINE']</span></code> attribute.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyDateField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">connection</span><span class="o">.</span><span class="n">settings_dict</span><span class="p">[</span><span class="s1">&#39;ENGINE&#39;</span><span class="p">]</span> <span class="o">==</span> <span class="s1">&#39;django.db.backends.mysql&#39;</span><span class="p">:</span>
            <span class="k">return</span> <span class="s1">&#39;datetime&#39;</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="s1">&#39;timestamp&#39;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">db_type()</span></code></a> and <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.rel_db_type" title="django.db.models.Field.rel_db_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rel_db_type()</span></code></a> methods are called by
Django when the framework constructs the <code class="docutils literal notranslate"><span class="pre">CREATE</span> <span class="pre">TABLE</span></code> statements for your
application – that is, when you first create your tables. The methods are also
called when constructing a <code class="docutils literal notranslate"><span class="pre">WHERE</span></code> clause that includes the model field –
that is, when you retrieve data using QuerySet methods like <code class="docutils literal notranslate"><span class="pre">get()</span></code>,
<code class="docutils literal notranslate"><span class="pre">filter()</span></code>, and <code class="docutils literal notranslate"><span class="pre">exclude()</span></code> and have the model field as an argument. They
are not called at any other time, so it can afford to execute slightly complex
code, such as the <code class="docutils literal notranslate"><span class="pre">connection.settings_dict</span></code> check in the above example.</p>
<p>Some database column types accept parameters, such as <code class="docutils literal notranslate"><span class="pre">CHAR(25)</span></code>, where the
parameter <code class="docutils literal notranslate"><span class="pre">25</span></code> represents the maximum column length. In cases like these,
it’s more flexible if the parameter is specified in the model rather than being
hard-coded in the <code class="docutils literal notranslate"><span class="pre">db_type()</span></code> method. For example, it wouldn’t make much
sense to have a <code class="docutils literal notranslate"><span class="pre">CharMaxlength25Field</span></code>, shown here:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># This is a silly example of hard-coded parameters.</span>
<span class="k">class</span> <span class="nc">CharMaxlength25Field</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;char(25)&#39;</span>

<span class="c1"># In the model:</span>
<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1"># ...</span>
    <span class="n">my_field</span> <span class="o">=</span> <span class="n">CharMaxlength25Field</span><span class="p">()</span>
</pre></div>
</div>
<p>The better way of doing this would be to make the parameter specifiable at run
time – i.e., when the class is instantiated. To do that, just implement
<code class="docutils literal notranslate"><span class="pre">Field.__init__()</span></code>, like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># This is a much more flexible example.</span>
<span class="k">class</span> <span class="nc">BetterCharField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">max_length</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">max_length</span> <span class="o">=</span> <span class="n">max_length</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;char(</span><span class="si">%s</span><span class="s1">)&#39;</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">max_length</span>

<span class="c1"># In the model:</span>
<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1"># ...</span>
    <span class="n">my_field</span> <span class="o">=</span> <span class="n">BetterCharField</span><span class="p">(</span><span class="mi">25</span><span class="p">)</span>
</pre></div>
</div>
<p>Finally, if your column requires truly complex SQL setup, return <code class="docutils literal notranslate"><span class="pre">None</span></code> from
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">db_type()</span></code></a>. This will cause Django’s SQL creation code to skip
over this field. You are then responsible for creating the column in the right
table in some other way, of course, but this gives you a way to tell Django to
get out of the way.</p>
<p>The <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.rel_db_type" title="django.db.models.Field.rel_db_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rel_db_type()</span></code></a> method is called by fields such as <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code>
and <code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code> that point to another field to determine their database
column data types. For example, if you have an <code class="docutils literal notranslate"><span class="pre">UnsignedAutoField</span></code>, you also
need the foreign keys that point to that field to use the same data type:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># MySQL unsigned integer (range 0 to 4294967295).</span>
<span class="k">class</span> <span class="nc">UnsignedAutoField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">AutoField</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;integer UNSIGNED AUTO_INCREMENT&#39;</span>

    <span class="k">def</span> <span class="nf">rel_db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;integer UNSIGNED&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-converting-values-to-python-objects">
<span id="s-id2"></span><span id="converting-values-to-python-objects"></span><span id="id2"></span><h4>Converting values to Python objects<a class="headerlink" href="#converting-values-to-python-objects" title="Permalink to this headline">¶</a></h4>
<p>If your custom <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> class deals with data structures that are more
complex than strings, dates, integers, or floats, then you may need to override
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.from_db_value" title="django.db.models.Field.from_db_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">from_db_value()</span></code></a> and <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><code class="xref py py-meth docutils literal notranslate"><span class="pre">to_python()</span></code></a>.</p>
<p>If present for the field subclass, <code class="docutils literal notranslate"><span class="pre">from_db_value()</span></code> will be called in all
circumstances when the data is loaded from the database, including in
aggregates and <a class="reference internal" href="../ref/models/querysets.html#django.db.models.query.QuerySet.values" title="django.db.models.query.QuerySet.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code></a> calls.</p>
<p><code class="docutils literal notranslate"><span class="pre">to_python()</span></code> is called by deserialization and during the
<a class="reference internal" href="../ref/models/instances.html#django.db.models.Model.clean" title="django.db.models.Model.clean"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clean()</span></code></a> method used from forms.</p>
<p>As a general rule, <code class="docutils literal notranslate"><span class="pre">to_python()</span></code> should deal gracefully with any of the
following arguments:</p>
<ul class="simple">
<li>An instance of the correct type (e.g., <code class="docutils literal notranslate"><span class="pre">Hand</span></code> in our ongoing example).</li>
<li>A string</li>
<li><code class="docutils literal notranslate"><span class="pre">None</span></code> (if the field allows <code class="docutils literal notranslate"><span class="pre">null=True</span></code>)</li>
</ul>
<p>In our <code class="docutils literal notranslate"><span class="pre">HandField</span></code> class, we’re storing the data as a VARCHAR field in the
database, so we need to be able to process strings and <code class="docutils literal notranslate"><span class="pre">None</span></code> in the
<code class="docutils literal notranslate"><span class="pre">from_db_value()</span></code>. In <code class="docutils literal notranslate"><span class="pre">to_python()</span></code>, we need to also handle <code class="docutils literal notranslate"><span class="pre">Hand</span></code>
instances:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">re</span>

<span class="kn">from</span> <span class="nn">django.core.exceptions</span> <span class="k">import</span> <span class="n">ValidationError</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.utils.translation</span> <span class="k">import</span> <span class="n">gettext_lazy</span> <span class="k">as</span> <span class="n">_</span>

<span class="k">def</span> <span class="nf">parse_hand</span><span class="p">(</span><span class="n">hand_string</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Takes a string of cards and splits into a full hand.&quot;&quot;&quot;</span>
    <span class="n">p1</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;.</span><span class="si">{26}</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="n">p2</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;..&#39;</span><span class="p">)</span>
    <span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="n">p2</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">p1</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">hand_string</span><span class="p">)]</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">4</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">ValidationError</span><span class="p">(</span><span class="n">_</span><span class="p">(</span><span class="s2">&quot;Invalid input for a Hand instance&quot;</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">Hand</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="c1"># ...</span>

    <span class="k">def</span> <span class="nf">from_db_value</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">expression</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">value</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">value</span>
        <span class="k">return</span> <span class="n">parse_hand</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">to_python</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">Hand</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">value</span>

        <span class="k">if</span> <span class="n">value</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">value</span>

        <span class="k">return</span> <span class="n">parse_hand</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>Notice that we always return a <code class="docutils literal notranslate"><span class="pre">Hand</span></code> instance from these methods. That’s the
Python object type we want to store in the model’s attribute.</p>
<p>For <code class="docutils literal notranslate"><span class="pre">to_python()</span></code>, if anything goes wrong during value conversion, you should
raise a <a class="reference internal" href="../ref/exceptions.html#django.core.exceptions.ValidationError" title="django.core.exceptions.ValidationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValidationError</span></code></a> exception.</p>
</div>
<div class="section" id="s-converting-python-objects-to-query-values">
<span id="s-id3"></span><span id="converting-python-objects-to-query-values"></span><span id="id3"></span><h4>Converting Python objects to query values<a class="headerlink" href="#converting-python-objects-to-query-values" title="Permalink to this headline">¶</a></h4>
<p>Since using a database requires conversion in both ways, if you override
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><code class="xref py py-meth docutils literal notranslate"><span class="pre">to_python()</span></code></a> you also have to override <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_prep_value()</span></code></a>
to convert Python objects back to query values.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="c1"># ...</span>

    <span class="k">def</span> <span class="nf">get_prep_value</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">l</span><span class="p">)</span> <span class="k">for</span> <span class="n">l</span> <span class="ow">in</span> <span class="p">(</span><span class="n">value</span><span class="o">.</span><span class="n">north</span><span class="p">,</span>
                <span class="n">value</span><span class="o">.</span><span class="n">east</span><span class="p">,</span> <span class="n">value</span><span class="o">.</span><span class="n">south</span><span class="p">,</span> <span class="n">value</span><span class="o">.</span><span class="n">west</span><span class="p">)])</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">If your custom field uses the <code class="docutils literal notranslate"><span class="pre">CHAR</span></code>, <code class="docutils literal notranslate"><span class="pre">VARCHAR</span></code> or <code class="docutils literal notranslate"><span class="pre">TEXT</span></code>
types for MySQL, you must make sure that <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_prep_value()</span></code></a>
always returns a string type. MySQL performs flexible and unexpected
matching when a query is performed on these types and the provided
value is an integer, which can cause queries to include unexpected
objects in their results. This problem cannot occur if you always
return a string type from <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_prep_value()</span></code></a>.</p>
</div>
</div>
<div class="section" id="s-converting-query-values-to-database-values">
<span id="s-id4"></span><span id="converting-query-values-to-database-values"></span><span id="id4"></span><h4>Converting query values to database values<a class="headerlink" href="#converting-query-values-to-database-values" title="Permalink to this headline">¶</a></h4>
<p>Some data types (for example, dates) need to be in a specific format
before they can be used by a database backend.
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_db_prep_value()</span></code></a> is the method where those conversions should
be made. The specific connection that will be used for the query is
passed as the <code class="docutils literal notranslate"><span class="pre">connection</span></code> parameter. This allows you to use
backend-specific conversion logic if it is required.</p>
<p>For example, Django uses the following method for its
<a class="reference internal" href="../ref/models/fields.html#django.db.models.BinaryField" title="django.db.models.BinaryField"><code class="xref py py-class docutils literal notranslate"><span class="pre">BinaryField</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">get_db_prep_value</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">connection</span><span class="p">,</span> <span class="n">prepared</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
    <span class="n">value</span> <span class="o">=</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">get_db_prep_value</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">connection</span><span class="p">,</span> <span class="n">prepared</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">value</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">connection</span><span class="o">.</span><span class="n">Database</span><span class="o">.</span><span class="n">Binary</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">value</span>
</pre></div>
</div>
<p>In case your custom field needs a special conversion when being saved that is
not the same as the conversion used for normal query parameters, you can
override <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_db_prep_save" title="django.db.models.Field.get_db_prep_save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_db_prep_save()</span></code></a>.</p>
</div>
<div class="section" id="s-preprocessing-values-before-saving">
<span id="s-id5"></span><span id="preprocessing-values-before-saving"></span><span id="id5"></span><h4>Preprocessing values before saving<a class="headerlink" href="#preprocessing-values-before-saving" title="Permalink to this headline">¶</a></h4>
<p>If you want to preprocess the value just before saving, you can use
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.pre_save" title="django.db.models.Field.pre_save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pre_save()</span></code></a>. For example, Django’s
<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateTimeField" title="django.db.models.DateTimeField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateTimeField</span></code></a> uses this method to set the attribute
correctly in the case of <a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField.auto_now" title="django.db.models.DateField.auto_now"><code class="xref py py-attr docutils literal notranslate"><span class="pre">auto_now</span></code></a> or
<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField.auto_now_add" title="django.db.models.DateField.auto_now_add"><code class="xref py py-attr docutils literal notranslate"><span class="pre">auto_now_add</span></code></a>.</p>
<p>If you do override this method, you must return the value of the attribute at
the end. You should also update the model’s attribute if you make any changes
to the value so that code holding references to the model will always see the
correct value.</p>
</div>
<div class="section" id="s-specifying-the-form-field-for-a-model-field">
<span id="s-specifying-form-field-for-model-field"></span><span id="specifying-the-form-field-for-a-model-field"></span><span id="specifying-form-field-for-model-field"></span><h4>Specifying the form field for a model field<a class="headerlink" href="#specifying-the-form-field-for-a-model-field" title="Permalink to this headline">¶</a></h4>
<p>To customize the form field used by <a class="reference internal" href="../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a>, you can
override <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.formfield" title="django.db.models.Field.formfield"><code class="xref py py-meth docutils literal notranslate"><span class="pre">formfield()</span></code></a>.</p>
<p>The form field class can be specified via the <code class="docutils literal notranslate"><span class="pre">form_class</span></code> and
<code class="docutils literal notranslate"><span class="pre">choices_form_class</span></code> arguments; the latter is used if the field has choices
specified, the former otherwise. If these arguments are not provided,
<a class="reference internal" href="../ref/forms/fields.html#django.forms.CharField" title="django.forms.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a> or <a class="reference internal" href="../ref/forms/fields.html#django.forms.TypedChoiceField" title="django.forms.TypedChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">TypedChoiceField</span></code></a>
will be used.</p>
<p>All of the <code class="docutils literal notranslate"><span class="pre">kwargs</span></code> dictionary is passed directly to the form field’s
<code class="docutils literal notranslate"><span class="pre">__init__()</span></code> method. Normally, all you need to do is set up a good default
for the <code class="docutils literal notranslate"><span class="pre">form_class</span></code> (and maybe <code class="docutils literal notranslate"><span class="pre">choices_form_class</span></code>) argument and then
delegate further handling to the parent class. This might require you to write
a custom form field (and even a form widget). See the <a class="reference internal" href="../topics/forms/index.html"><span class="doc">forms documentation</span></a> for information about this.</p>
<p>Continuing our ongoing example, we can write the <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.formfield" title="django.db.models.Field.formfield"><code class="xref py py-meth docutils literal notranslate"><span class="pre">formfield()</span></code></a> method
as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="c1"># ...</span>

    <span class="k">def</span> <span class="nf">formfield</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="c1"># This is a fairly standard way to set up some defaults</span>
        <span class="c1"># while letting the caller override them.</span>
        <span class="n">defaults</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;form_class&#39;</span><span class="p">:</span> <span class="n">MyFormField</span><span class="p">}</span>
        <span class="n">defaults</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">formfield</span><span class="p">(</span><span class="o">**</span><span class="n">defaults</span><span class="p">)</span>
</pre></div>
</div>
<p>This assumes we’ve imported a <code class="docutils literal notranslate"><span class="pre">MyFormField</span></code> field class (which has its own
default widget). This document doesn’t cover the details of writing custom form
fields.</p>
</div>
<div class="section" id="s-emulating-built-in-field-types">
<span id="s-id6"></span><span id="emulating-built-in-field-types"></span><span id="id6"></span><h4>Emulating built-in field types<a class="headerlink" href="#emulating-built-in-field-types" title="Permalink to this headline">¶</a></h4>
<p>If you have created a <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">db_type()</span></code></a> method, you don’t need to worry about
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_internal_type" title="django.db.models.Field.get_internal_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_internal_type()</span></code></a> – it won’t be used much. Sometimes, though, your
database storage is similar in type to some other field, so you can use that
other field’s logic to create the right column.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="c1"># ...</span>

    <span class="k">def</span> <span class="nf">get_internal_type</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;CharField&#39;</span>
</pre></div>
</div>
<p>No matter which database backend we are using, this will mean that
<a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">migrate</span></code></a> and other SQL commands create the right column type for
storing a string.</p>
<p>If <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_internal_type" title="django.db.models.Field.get_internal_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_internal_type()</span></code></a> returns a string that is not known to Django for
the database backend you are using – that is, it doesn’t appear in
<code class="docutils literal notranslate"><span class="pre">django.db.backends.&lt;db_name&gt;.base.DatabaseWrapper.data_types</span></code> – the string
will still be used by the serializer, but the default <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">db_type()</span></code></a>
method will return <code class="docutils literal notranslate"><span class="pre">None</span></code>. See the documentation of <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">db_type()</span></code></a>
for reasons why this might be useful. Putting a descriptive string in as the
type of the field for the serializer is a useful idea if you’re ever going to
be using the serializer output in some other place, outside of Django.</p>
</div>
<div class="section" id="s-converting-field-data-for-serialization">
<span id="s-converting-model-field-to-serialization"></span><span id="converting-field-data-for-serialization"></span><span id="converting-model-field-to-serialization"></span><h4>Converting field data for serialization<a class="headerlink" href="#converting-field-data-for-serialization" title="Permalink to this headline">¶</a></h4>
<p>To customize how the values are serialized by a serializer, you can override
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.value_to_string" title="django.db.models.Field.value_to_string"><code class="xref py py-meth docutils literal notranslate"><span class="pre">value_to_string()</span></code></a>. Using <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.value_from_object" title="django.db.models.Field.value_from_object"><code class="xref py py-meth docutils literal notranslate"><span class="pre">value_from_object()</span></code></a> is the
best way to get the field’s value prior to serialization. For example, since
<code class="docutils literal notranslate"><span class="pre">HandField</span></code> uses strings for its data storage anyway, we can reuse some
existing conversion code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="c1"># ...</span>

    <span class="k">def</span> <span class="nf">value_to_string</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">):</span>
        <span class="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">value_from_object</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_prep_value</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-some-general-advice">
<span id="some-general-advice"></span><h3>Some general advice<a class="headerlink" href="#some-general-advice" title="Permalink to this headline">¶</a></h3>
<p>Writing a custom field can be a tricky process, particularly if you’re doing
complex conversions between your Python types and your database and
serialization formats. Here are a couple of tips to make things go more
smoothly:</p>
<ol class="arabic simple">
<li>Look at the existing Django fields (in
<code class="file docutils literal notranslate"><span class="pre">django/db/models/fields/__init__.py</span></code>) for inspiration. Try to find
a field that’s similar to what you want and extend it a little bit,
instead of creating an entirely new field from scratch.</li>
<li>Put a <code class="docutils literal notranslate"><span class="pre">__str__()</span></code> method on the class you’re wrapping up as a field. There
are a lot of places where the default behavior of the field code is to call
<code class="docutils literal notranslate"><span class="pre">str()</span></code> on the value. (In our examples in this document, <code class="docutils literal notranslate"><span class="pre">value</span></code> would
be a <code class="docutils literal notranslate"><span class="pre">Hand</span></code> instance, not a <code class="docutils literal notranslate"><span class="pre">HandField</span></code>). So if your <code class="docutils literal notranslate"><span class="pre">__str__()</span></code>
method automatically converts to the string form of your Python object, you
can save yourself a lot of work.</li>
</ol>
</div>
</div>
<div class="section" id="s-writing-a-filefield-subclass">
<span id="writing-a-filefield-subclass"></span><h2>Writing a <code class="docutils literal notranslate"><span class="pre">FileField</span></code> subclass<a class="headerlink" href="#writing-a-filefield-subclass" title="Permalink to this headline">¶</a></h2>
<p>In addition to the above methods, fields that deal with files have a few other
special requirements which must be taken into account. The majority of the
mechanics provided by <code class="docutils literal notranslate"><span class="pre">FileField</span></code>, such as controlling database storage and
retrieval, can remain unchanged, leaving subclasses to deal with the challenge
of supporting a particular type of file.</p>
<p>Django provides a <code class="docutils literal notranslate"><span class="pre">File</span></code> class, which is used as a proxy to the file’s
contents and operations. This can be subclassed to customize how the file is
accessed, and what methods are available. It lives at
<code class="docutils literal notranslate"><span class="pre">django.db.models.fields.files</span></code>, and its default behavior is explained in the
<a class="reference internal" href="../ref/files/file.html"><span class="doc">file documentation</span></a>.</p>
<p>Once a subclass of <code class="docutils literal notranslate"><span class="pre">File</span></code> is created, the new <code class="docutils literal notranslate"><span class="pre">FileField</span></code> subclass must be
told to use it. To do so, simply assign the new <code class="docutils literal notranslate"><span class="pre">File</span></code> subclass to the special
<code class="docutils literal notranslate"><span class="pre">attr_class</span></code> attribute of the <code class="docutils literal notranslate"><span class="pre">FileField</span></code> subclass.</p>
<div class="section" id="s-a-few-suggestions">
<span id="a-few-suggestions"></span><h3>A few suggestions<a class="headerlink" href="#a-few-suggestions" title="Permalink to this headline">¶</a></h3>
<p>In addition to the above details, there are a few guidelines which can greatly
improve the efficiency and readability of the field’s code.</p>
<ol class="arabic simple">
<li>The source for Django’s own <code class="docutils literal notranslate"><span class="pre">ImageField</span></code> (in
<code class="docutils literal notranslate"><span class="pre">django/db/models/fields/files.py</span></code>) is a great example of how to
subclass <code class="docutils literal notranslate"><span class="pre">FileField</span></code> to support a particular type of file, as it
incorporates all of the techniques described above.</li>
<li>Cache file attributes wherever possible. Since files may be stored in
remote storage systems, retrieving them may cost extra time, or even
money, that isn’t always necessary. Once a file is retrieved to obtain
some data about its content, cache as much of that data as possible to
reduce the number of times the file must be retrieved on subsequent
calls for that information.</li>
</ol>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Writing custom model fields</a><ul>
<li><a class="reference internal" href="#introduction">Introduction</a><ul>
<li><a class="reference internal" href="#our-example-object">Our example object</a></li>
</ul>
</li>
<li><a class="reference internal" href="#background-theory">Background theory</a><ul>
<li><a class="reference internal" href="#database-storage">Database storage</a></li>
<li><a class="reference internal" href="#what-does-a-field-class-do">What does a field class do?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#writing-a-field-subclass">Writing a field subclass</a><ul>
<li><a class="reference internal" href="#field-deconstruction">Field deconstruction</a></li>
<li><a class="reference internal" href="#changing-a-custom-field-s-base-class">Changing a custom field’s base class</a></li>
<li><a class="reference internal" href="#documenting-your-custom-field">Documenting your custom field</a></li>
<li><a class="reference internal" href="#useful-methods">Useful methods</a><ul>
<li><a class="reference internal" href="#custom-database-types">Custom database types</a></li>
<li><a class="reference internal" href="#converting-values-to-python-objects">Converting values to Python objects</a></li>
<li><a class="reference internal" href="#converting-python-objects-to-query-values">Converting Python objects to query values</a></li>
<li><a class="reference internal" href="#converting-query-values-to-database-values">Converting query values to database values</a></li>
<li><a class="reference internal" href="#preprocessing-values-before-saving">Preprocessing values before saving</a></li>
<li><a class="reference internal" href="#specifying-the-form-field-for-a-model-field">Specifying the form field for a model field</a></li>
<li><a class="reference internal" href="#emulating-built-in-field-types">Emulating built-in field types</a></li>
<li><a class="reference internal" href="#converting-field-data-for-serialization">Converting field data for serialization</a></li>
</ul>
</li>
<li><a class="reference internal" href="#some-general-advice">Some general advice</a></li>
</ul>
</li>
<li><a class="reference internal" href="#writing-a-filefield-subclass">Writing a <code class="docutils literal notranslate"><span class="pre">FileField</span></code> subclass</a><ul>
<li><a class="reference internal" href="#a-few-suggestions">A few suggestions</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="custom-management-commands.html"
                        title="previous chapter">Writing custom <code class="docutils literal notranslate"><span class="pre">django-admin</span></code> commands</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="custom-lookups.html"
                        title="next chapter">Custom Lookups</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/custom-model-fields.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Mar 04, 2020</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="custom-management-commands.html" title="Writing custom &lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;django-admin&lt;/span&gt;&lt;/code&gt; commands">previous</a>
     |
    <a href="index.html" title="“How-to” guides" accesskey="U">up</a>
   |
    <a href="custom-lookups.html" title="Custom Lookups">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>